package com.lvyq.qrobot.service.impl;

import com.lvyq.qrobot.common.StatusConst;
import com.lvyq.qrobot.common.UrlConstant;
import com.lvyq.qrobot.entity.*;
import com.lvyq.qrobot.mapper.*;
import com.lvyq.qrobot.model.receive.ReceiveMsg;
import com.lvyq.qrobot.model.send.SendParam;
import com.lvyq.qrobot.service.UserAttributeService;
import com.lvyq.qrobot.service.UserGovAffairService;
import com.lvyq.qrobot.service.UserService;
import com.lvyq.qrobot.util.DateUtil;
import com.lvyq.qrobot.util.HttpClientUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvyq 用户操作
 * @version 1.0
 * Create by 2024-05-31 14:41
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    public UserMapper userMapper;

    @Resource
    public UserGovAffairService userGovAffairService;

    @Resource
    public SysEquipMapper sysEquipMapper;

    @Resource
    public UserEquipMapper userEquipMapper;

    @Resource
    public UserAttributeService userAttributeService;

    @Resource
    public UserAttributeMapper userAttributeMapper;

    @Resource
    public SysGiftPackMapper sysGiftPackMapper;

    /**
     * @description 打卡
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-05-31 15:09
     */
    @Override
    public void singIn(SysOrder order,SendParam param, ReceiveMsg vo) {
        UserEntity user = getUser(vo);
        String content="";
        if (user.singIn==StatusConst.SING_IN){
            //已打卡
            content="[CQ:at,qq="+user.userId.toString()+"]\n您今日已上朝,明天再来吧。";
        }else {
            content=order.content.replace("{1}",user.userId.toString())
                    .replace("{2}",user.fenglu.toString());
            user.setYinliang(user.yinliang+user.fenglu);
            user.setSingIn(StatusConst.SING_IN);
            userMapper.updateById(user);
        }
        param.setMessage(content);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }


    /**
     * @description 获取用户信息，不存在时则创建
     * @author lvyq
     * @param[1] vo
     * @throws
     * @return UserEntity
     * @time 2024-05-31 15:29
     */
    @Override
    @Transactional
    public UserEntity getUser(ReceiveMsg vo) {
        UserEntity user = userMapper.selectByUserId(vo.userId,vo.groupId);
        if (user==null){
            user=new UserEntity();
            user = new UserEntity();
            user.setGroupId(vo.groupId);
            user.setNickName(vo.sender.nickname);
            user.setUserId(vo.userId);
            user.setJingyan(0);
            user.setDengji(1);
            user.setSingIn(StatusConst.SING_NOT);
            user.setTili(100);
            user.setPosition("士卒");
            user.setPositionLevel(1);
            user.setGongxun(0);
            user.setChengjiu("您还没有成就");
            user.setChengwei("您还没有称谓");
            user.setPinji("未入品");
            user.setAffairNum(10);
            user.setAffairingNum(0);
            user.setFenglu(100);
            user.setYinliang(0);
            user.setPhoto("");
            user.setGiftPackNum(0);
            user.setGiftNextTime(new Date().getTime());
            user.setSkillPoint(0);
            userMapper.insert(user);

            //任务装备初始化
            List<SysEquip> equips = sysEquipMapper.listByLevel(1);
            //属性初始化
            UserEntity finalUser = user;
            equips.forEach(sysEquip -> {
                UserEquip userEquip = new UserEquip();
                userEquip.setGroupId(finalUser.groupId);
                userEquip.setUserId(finalUser.userId);
                userEquip.setEquipName(sysEquip.name);
                userEquip.setFortifyLevel(0);
                userEquip.setPart(sysEquip.part);
                userEquipMapper.insert(userEquip);
            });
            //人物属性初始化
            userAttributeService.initAttribute(equips,vo);
        }
        return user;
    }

    /**
     * @description 人员操作相关
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-06-04 10:15
     */
    @Override
    public void sendMsg(SysOrder order, SendParam param, ReceiveMsg vo) {
        //上朝
        if ("上朝".equals(vo.message)){
            singIn(order,param,vo);
        }
        if ("穿越".equals(vo.message)){
            over(order.getContent(),param,vo);
        }
        if ("属性".equals(vo.message)){
            userAttribute(order.content,param,vo);
        }
        if ("升级".equals(vo.message)){
            upLevel(order.content,param,vo);
        }
        if ("领取".equals(vo.message)){
            giftPack(order.content,param,vo);
        }
    }

    /**
     * @description 领取每日礼包
     * @author lvyq
     * @throws
     * @time 2024-06-06 13:54
     */
    private void giftPack(String content, SendParam param, ReceiveMsg vo) {
        UserEntity user = getUser(vo);
        Long startTime = new Date().getTime();

        if (user.giftPackNum<7){
            if (user.giftNextTime<new Date().getTime()){
                SysGiftPack infoByLevel = sysGiftPackMapper.getInfoByLevel(user.getGiftPackNum() + 1);

                Long endTime = startTime+infoByLevel.time*1000*60;

                if (user.getGiftPackNum()==6){
                    content=content.replace("{1}",vo.userId.toString())
                            .replace("{2}",infoByLevel.jingyan.toString())
                            .replace("{3}",infoByLevel.yinliang.toString())
                            .replace("{4}",infoByLevel.tili.toString())
                            .replace("{5}后可再次领取","今日礼包全部领取");
                }else {
                    content=content.replace("{1}",vo.userId.toString())
                            .replace("{2}",infoByLevel.jingyan.toString())
                            .replace("{3}",infoByLevel.yinliang.toString())
                            .replace("{4}",infoByLevel.tili.toString())
                            .replace("{5}",DateUtil.timeChange(endTime));
                }
                user.setGiftPackNum(user.giftPackNum+1);
                user.setJingyan(user.jingyan+ infoByLevel.getJingyan());
                Integer tili = user.tili+ infoByLevel.getTili();
                if (tili>100){
                    tili=100;
                }
                user.setTili(tili);
                user.setGiftNextTime(endTime);
                userMapper.updateById(user);
            }else {
                content = "[CQ:at,qq="+vo.userId+"]\n今日礼包领取失败,距离下次领取还需"+DateUtil.timeChange(user.giftNextTime);
            }

        }else {
            content = "[CQ:at,qq="+vo.userId+"]\n今日礼包已全部领取完毕";
        }

        param.setMessage(content);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 升级，每升一级，体力恢复为100，并且气血+1
     * @author lvyq
     * @param[1] content
     * @param[2] param
     * @param[3] vo
     * @throws
     * @time 2024-06-05 16:39
     */
    private void upLevel(String content, SendParam param, ReceiveMsg vo) {
        UserEntity user = getUser(vo);
        Integer nowLevel = user.dengji;
        Integer needExp = 0;
        if (nowLevel<10){
            needExp = user.dengji*100;
        }else if (nowLevel<20){
            needExp=user.dengji*100*2;
        }

        if (user.jingyan<needExp){
            content="[CQ:at,qq="+vo.userId+"]\n经验不足,升级失败";
        }else{
            user.setJingyan(user.jingyan-needExp);
            user.setTili(100);
            user.setDengji(user.dengji+1);
            userMapper.updateById(user);
            //修改属性
            UserAttribute userAttribute = userAttributeService.getUserAttributeInfo(vo.groupId,vo.userId);
            userAttribute.setBlood(userAttribute.blood+ user.dengji-1);
            userAttributeMapper.updateById(userAttribute);
            content=content.replace("{1}",vo.userId.toString())
                    .replace("{2}",user.dengji.toString());
        }
        param.setMessage(content);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 属性
     * @author lvyq
     * @param[1] content
     * @param[2] param
     * @param[3] vo
     * @throws

     * @time 2024-06-05 16:10
     */
    private void userAttribute(String content, SendParam param, ReceiveMsg vo) {
        UserEntity user = getUser(vo);
        UserAttribute att = userAttributeService.getUserAttributeInfo(vo.groupId,vo.userId);
        List<UserEquip> equip = userEquipMapper.getUserEquipInfo(vo.groupId,vo.userId);
        Map<String,Object> eqMap = new HashMap<>();
        equip.forEach(e->{
            eqMap.put(e.part,e.equipName+"(+"+e.fortifyLevel+")");
        });
        content = content.replace("{1}",vo.userId.toString())
                .replace("{2}",user.dengji.toString())
                .replace("{3}",att.basicAttack.toString())
                .replace("{4}",att.defense.toString())
                .replace("{5}",att.blood.toString())
                .replace("{6}",att.internalForce.toString())
                .replace("{7}",att.criticalStrike.toString())
                .replace("{8}",att.dodge.toString())
                .replace("{9}",att.basicFirstAttack.toString())
                .replace("{10}",att.antiRiot.toString())
                .replace("{11}",att.hit.toString())
                .replace("{12}","2")
                .replace("{13}",eqMap.get(StatusConst.EQUIP_HAND).toString())
                .replace("{14}",eqMap.get(StatusConst.EQUIP_HEAD).toString())
                .replace("{15}",eqMap.get(StatusConst.EQUIP_DRESS).toString())
                .replace("{16}",eqMap.get(StatusConst.EQUIP_BELT).toString())
                .replace("{17}",eqMap.get(StatusConst.EQUIP_NECKLACE).toString());
        param.setMessage(content);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 穿越
     * @author lvyq
     * @throws
     * @time 2024-06-04 11:00
     */
    private void over(String content, SendParam param, ReceiveMsg vo) {
        UserEntity user = getUser(vo);
        StringBuffer guanzhi = new StringBuffer();
        guanzhi.append(user.position+"("+user.pinji+")");
        if (user.singIn==StatusConst.SING_NOT){
            guanzhi.append("[上朝]");
        }
        //图片
        StringBuffer photo = new StringBuffer();
        if (user.photo!=null && !"".equals(user.photo)){
            photo.append("[CQ:image,file=59b622be4143c574431e1224b1b72f82,subType=13,type=original,url=http://gchat.qpic.cn/gchatpic_new/0/0-0-59B622BE4143C574431E1224B1B72F82/0?term=2]");
        }
        StringBuffer giftPack = new StringBuffer();
        //每日任务
        if (user.getGiftPackNum()<7){
            if (user.giftNextTime<new Date().getTime()){
                giftPack.append("❗️[领取]");
            }else {
                giftPack.append("(剩余"+DateUtil.timeChange(user.giftNextTime)+")");
            }

        }else {
            giftPack.append("(无)");
        }

        //功勋

        //政务
        StringBuffer userGovAffair = new StringBuffer();
        UserGovAffair info = userGovAffairService.getInfo(vo);
        //查询是否有政务
        if (info!=null){
            userGovAffair.append(info.name+"(剩"+DateUtil.timeChange(info.end)+")");
        }else {
            userGovAffair.append("无");
        }

        //经验
        String exp = "";
        Integer nowLevel=user.dengji;
        Integer needExp = 0;
        if (nowLevel<10){
            needExp = user.dengji*100;
        }else if (nowLevel<20){
            needExp=user.dengji*100*2;
        }

        if (user.jingyan>=needExp){
            exp=user.jingyan+"/"+needExp+"("+user.dengji+"级)[升级]";
        }else {
            exp=user.jingyan+"/"+needExp+"("+user.dengji+"级)";
        }


        content=content.replace("{1}",vo.userId.toString())
                .replace("{2}",photo.toString())
                .replace("{3}",user.nickName+"(白名)")
                .replace("{4}",guanzhi)
                .replace("{5}",user.gongxun+"/100")
                .replace("{6}",user.chengjiu)
                .replace("{7}",user.chengwei)
                .replace("{8}",user.tili+"/100")
                .replace("{9}",userGovAffair)
                //升级所需经验为当前等级*100
                .replace("{10}",exp)
                .replace("{11}",giftPack.toString());
        param.setMessage(content);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }


}
